﻿// //------------------------------------------------------------------------------
// // <copyright file="" company="Dascoba Development">
// //  Copyright © Dascoba Development 2010
// // </copyright>
// //------------------------------------------------------------------------------
namespace Dascoba.Umb.FileManager.Config
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Xml;

    using Dascoba.Umb.FileManager.Support;

    using umbraco.BusinessLogic;

    /// <summary>
    ///   Wraps the Config File
    /// </summary>
    public class FileManagerConfig : XmlDocument
    {
        /// <summary>
        ///   Gets an instance of FileManagerConfig.
        /// </summary>
        /// <value>The instance.</value>
        private static FileManagerConfig Instance
        {
            get
            {
                var config = new FileManagerConfig();
                config.Load(Util.MapPath("/config/fileManager.config"));
                return config;
            }
        }

        #region Internal Properties

        /// <summary>
        ///   Gets the umbraco tree aliases.
        /// </summary>
        /// <value>The umbraco tree aliases.</value>
        internal static ICollection<string> UmbracoTreeAliases
        {
            get
            {
                if (Instance.DocumentElement == null)
                {
                    return new List<string>();
                }
                var treeNodes = Instance.DocumentElement.SelectSingleNode("umbracoTrees").ChildNodes;
                return (from XmlNode node in treeNodes select node.Attributes["alias"].Value).ToList();
            }
        }

        /// <summary>
        ///   Gets a value indicating whether [hide unknown files].
        /// </summary>
        /// <value><c>true</c> if [hide unknown files]; otherwise, <c>false</c>.</value>
        internal static bool HideUnknownFiles
        {
            get
            {
                if (Instance.DocumentElement == null)
                {
                    return false;
                }

                return
                    Convert.ToBoolean(
                        Instance.DocumentElement.SelectSingleNode("filePages").Attributes["hideUnknown"].Value);
            }
        }

        /// <summary>
        ///   Gets a value indicating whether [umbraco trees enabled].
        /// </summary>
        /// <value><c>true</c> if [umbraco trees enabled]; otherwise, <c>false</c>.</value>
        internal static bool UmbracoTreesEnabled
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                return configRoot != null &&
                       Convert.ToBoolean(configRoot.SelectSingleNode("umbracoTrees").Attributes["enabled"].Value);
            }
        }

        /// <summary>
        /// Gets a value indicating whether [edit area enabled].
        /// </summary>
        /// <value><c>true</c> if [edit area enabled]; otherwise, <c>false</c>.</value>
        public static bool EditAreaDisplay
        {
            get
            {
                var configRoot = Instance.DocumentElement;

                return configRoot != null &&
                       Convert.ToBoolean(configRoot.SelectSingleNode("editAreaSyntax").Attributes["enabled"].Value);
            }
        }

        /// <summary>
        /// Gets a value indicating whether [edit area allow toggle].
        /// </summary>
        /// <value>
        /// 	<c>true</c> if [edit area allow toggle]; otherwise, <c>false</c>.
        /// </value>
        public static bool EditAreaAllowToggle
        {
            get
            {
                var configRoot = Instance.DocumentElement;

                return configRoot != null &&
                       Convert.ToBoolean(configRoot.SelectSingleNode("editAreaSyntax").Attributes["allowToggle"].Value);
            }
        }

        /// <summary>
        /// Gets a value indicating whether [edit area word wrap].
        /// </summary>
        /// <value><c>true</c> if [edit area word wrap]; otherwise, <c>false</c>.</value>
        public static bool EditAreaWordWrap
        {
            get
            {
                var configRoot = Instance.DocumentElement;

                return configRoot != null &&
                       Convert.ToBoolean(configRoot.SelectSingleNode("editAreaSyntax").Attributes["wordWrap"].Value);
            }
        }

        /// <summary>
        /// Gets the edit area language.
        /// </summary>
        /// <value>The edit area language.</value>
        public static string EditAreaLanguage
        {
            get
            {
                var configRoot = Instance.DocumentElement;

                return configRoot != null ? configRoot.SelectSingleNode("editAreaSyntax").Attributes["language"].Value : "en";
            }
        }

        /// <summary>
        ///   Gets the file opener collection.
        /// </summary>
        /// <value>The file openers.</value>
        internal static ICollection<FileOpener> FileOpeners
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                if (configRoot == null)
                {
                    return new List<FileOpener>();
                }
                var faNodes = configRoot.SelectSingleNode("filePages").ChildNodes;

                return (from XmlNode node in faNodes
                        select
                            new FileOpener
                                {
                                    Page = node.Attributes["page"] != null ? node.Attributes["page"].Value : String.Empty,
                                    OpenModal = node.Attributes["openModal"] != null
                                            ? Convert.ToBoolean(node.Attributes["openModal"].Value)
                                            : false,
                                    Function = node.Attributes["function"] != null
                                            ? node.Attributes["function"].Value
                                            : String.Empty,
                                    Name = node.Attributes["name"] != null ? node.Attributes["name"].Value : String.Empty,
                                    FileType = node.Attributes["fileType"] != null ? node.Attributes["fileType"].Value : String.Empty,
                                    Icon = node.Attributes["icon"] != null ? node.Attributes["icon"].Value : String.Empty,
                                    Extensions = node.Attributes["extensions"] != null
                                            ? Util.CleanLowerString(node.Attributes["extensions"].Value).Split(',')
                                            : new string[] { }
                                }).ToList();
            }
        }

        /// <summary>
        ///   Gets the default file function.
        /// </summary>
        /// <value>The default file function.</value>
        internal static string DefaultFileFunction
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                return configRoot == null
                           ? String.Empty
                           : configRoot.SelectSingleNode("filePages").Attributes["defaultFunction"].Value;
            }
        }

        /// <summary>
        ///   Gets the default file page.
        /// </summary>
        /// <value>The default file page.</value>
        internal static string DefaultFilePage
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                return configRoot == null
                           ? String.Empty
                           : configRoot.SelectSingleNode("filePages").Attributes["defaultPage"].Value;
            }
        }

        /// <summary>
        ///   Gets the current user root URL.
        /// </summary>
        /// <value>The current user root URL.</value>
        internal static string CurrentUserRootUrl
        {
            get
            {
                return GetUserRootUrl(User.GetCurrent());
            }
        }

        /// <summary>
        ///   Gets the current user root path.
        /// </summary>
        /// <returns></returns>
        internal static string CurrentUserRootPath
        {
            get
            {
                return Util.MapPath(CurrentUserRootUrl);
            }
        }

        /// <summary>
        ///   Gets the default root.
        /// </summary>
        /// <value>The default root.</value>
        internal static string DefaultRootUrl
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                return configRoot == null ? "/" : configRoot.SelectSingleNode("defaultRoot").Attributes["path"].Value;
            }
        }

        #endregion

        #region Internal Methods

        /// <summary>
        ///   Determines whether [has visible items] [the specified directory info].
        /// </summary>
        /// <param name = "directoryInfo">The directory info.</param>
        /// <param name = "onlyFolders">if set to <c>true</c> [only folders].</param>
        /// <param name = "visibleFiles">if set to <c>true</c> [contains files].</param>
        /// <param name = "visibleFolders"></param>
        /// <returns>
        ///   <c>true</c> if [has visible items] [the specified directory info]; otherwise, <c>false</c>.
        /// </returns>
        internal static bool HasVisibleItems(
            DirectoryInfo directoryInfo, bool onlyFolders, out bool visibleFiles, out bool visibleFolders)
        {
            visibleFolders = directoryInfo.GetDirectories().Any(IsFolderVisible);

            if (onlyFolders)
            {
                visibleFiles = false;
                return visibleFolders;
            }

            visibleFiles = directoryInfo.GetFiles().Any(IsFileVisible);

            return visibleFolders || visibleFiles;
        }

        /// <summary>
        ///   Determines whether [is folder visible] [the specified folder URL].
        /// </summary>
        /// <param name = "folderUrl">The folder URL.</param>
        /// <returns>
        ///   <c>true</c> if [is folder visible] [the specified folder URL]; otherwise, <c>false</c>.
        /// </returns>
        internal static bool IsFolderVisible(string folderUrl)
        {
            var currentUser = User.GetCurrent();

            folderUrl = folderUrl.ToLower();

            if (GlobalHideEnabled)
            {
                if (HiddenFolderPaths.Contains(folderUrl))
                {
                    return false;
                }
            }

            if (UserPermissionsEnabled)
            {
                var userFolders = GetUserFolders(currentUser.LoginName);
                var userTypeFolders = GetUserTypeFolders(currentUser.UserType.Alias);

                if (userFolders.Count > 0 || userTypeFolders.Count > 0)
                {
                    if (userFolders.Contains(folderUrl) || userTypeFolders.Contains(folderUrl))
                    {
                        return true;
                    }
                }
            }

            if (SectionRelationsEnabled)
            {
                var sectionAliases = GetFolderSectionAliases(folderUrl);
                if (sectionAliases.Count > 0)
                {
                    return currentUser.Applications.Any(application => sectionAliases.Contains(application.alias));
                }
            }

            return true;
        }

        /// <summary>
        ///   Determines whether [is folder visible] [the specified section aliases].
        /// </summary>
        /// <param name = "directoryInfo">The directory info.</param>
        /// <returns><c>true</c> if [is folder visible] [the specified section aliases]; otherwise, <c>false</c>.</returns>
        internal static bool IsFolderVisible(DirectoryInfo directoryInfo)
        {
            var folderUrl = Util.MapUrl(directoryInfo.FullName);

            return IsFolderVisible(folderUrl);
        }

        /// <summary>
        ///   Determines whether [is file visible] [the specified file URL].
        /// </summary>
        /// <param name = "fileUrl">The file URL.</param>
        /// <returns>
        ///   <c>true</c> if [is file visible] [the specified file URL]; otherwise, <c>false</c>.
        /// </returns>
        internal static bool IsFileVisible(string fileUrl)
        {
            if (Path.GetFileName(fileUrl) == Constants.RecycleBinConfigName)
            {
                return false;
            }

            var user = User.GetCurrent();
            fileUrl = fileUrl.ToLower();
            var fileExtension = Util.GetSimpleExtension(Util.MapPath(fileUrl)).ToLower();

            if (GlobalHideEnabled)
            {
                var hiddenFilePaths = HiddenFilePaths;
                if (hiddenFilePaths.Count > 0)
                {
                    if (hiddenFilePaths.Contains(fileUrl))
                    {
                        return false;
                    }
                }

                var hiddenFileExtensions = HiddenFileExtensions;
                if (hiddenFileExtensions.Count > 0)
                {
                    if (hiddenFileExtensions.Contains(fileExtension))
                    {
                        return false;
                    }
                }
            }

            // Check if file or extension is listed for provided user
            if (UserPermissionsEnabled)
            {
                var userFiles = GetUserFiles(user.LoginName);
                var userExtensions = GetUserExtensions(user.LoginName);
                var userTypeFiles = GetUserTypeFiles(user.UserType.Alias);
                var userTypeExtensions = GetUserTypeExtensions(user.UserType.Alias);

                if (userFiles.Contains(fileUrl) || userExtensions.Contains(fileExtension) ||
                    userTypeFiles.Contains(fileUrl) || userTypeExtensions.Contains(fileExtension))
                {
                    return true;
                }
            }

            // Check if file or extension is listed for user sections
            if (SectionRelationsEnabled)
            {
                var sectionAliases = GetFileSectionAliases(fileUrl);
                var sectionAliasesExt = GetExtensionSectionAliases(fileExtension);

                var sectionFileVisible = true;

                if (sectionAliases.Count > 0)
                {
                    sectionFileVisible = user.Applications.Any(
                        application => sectionAliases.Contains(application.alias));
                }

                if (sectionFileVisible)
                {
                    if (sectionAliasesExt.Count > 0)
                    {
                        return user.Applications.Any(application => sectionAliasesExt.Contains(application.alias));
                    }
                }
                else
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        ///   Determines whether [is file visible] [the specified file info].
        /// </summary>
        /// <param name = "fileInfo">The file info.</param>
        /// <returns><c>true</c> if [is file visible] [the specified file info]; otherwise, <c>false</c>.</returns>
        internal static bool IsFileVisible(FileInfo fileInfo)
        {
            var fileUrl = Util.MapUrl(fileInfo.FullName);
            return IsFileVisible(fileUrl);
        }

        /// <summary>
        ///   Gets the user root URL.
        /// </summary>
        /// <param name = "user">The user.</param>
        /// <returns></returns>
        internal static string GetUserRootUrl(User user)
        {
            DataHelper.AssureRootRecordExists(user.Id);

            string userRoot;
            if (UserPermissionsEnabled)
            {
                var configRoot = Instance.DocumentElement;
                if (configRoot == null)
                {
                    userRoot = String.Empty;
                }
                else
                {
                    var node =
                        configRoot.SelectSingleNode(
                            String.Format("userPermissions/addUser[@name='{0}']", user.LoginName));

                    userRoot = node != null ? node.Attributes["root"].Value : DataHelper.GetUserRoot(user.Id);
                }
            }
            else
            {
                userRoot = DataHelper.GetUserRoot(user.Id);
            }

            if (userRoot == String.Empty)
            {
                userRoot = DefaultRootUrl;
            }

            return userRoot;
        }

        /// <summary>
        ///   Gets the umbraco tree alias.
        /// </summary>
        /// <param name = "folderUrl">The folder URL.</param>
        /// <returns></returns>
        internal static string GetUmbracoTreeAlias(string folderUrl)
        {
            var configRoot = Instance.DocumentElement;

            if (!UmbracoTreesEnabled)
            {
                return String.Empty;
            }

            if (configRoot == null)
            {
                return String.Empty;
            }

            var nodes = configRoot.SelectSingleNode("umbracoTrees").ChildNodes;

            foreach (var treeNode in
                nodes.Cast<XmlNode>().Where(treeNode => treeNode.Attributes["path"].Value == folderUrl))
            {
                return treeNode.Attributes["alias"].Value;
            }

            return String.Empty;
        }

        /// <summary>
        ///   Gets the syntax parser for EditArea.
        /// </summary>
        /// <param name = "extension">The extension.</param>
        /// <returns></returns>
        internal static string GetSyntaxParser(string extension)
        {
            var configRoot = Instance.DocumentElement;

            if (configRoot == null)
            {
                return String.Empty;
            }

            var nodes = configRoot.SelectSingleNode("editAreaSyntax").ChildNodes;

            foreach (var parserNode in from XmlNode parserNode in nodes
                                       let extensions = parserNode.Attributes["extensions"].Value.ToLower().Split(',')
                                       where extensions.Contains(extension.ToLower())
                                       select parserNode)
            {
                return parserNode.Attributes["name"].Value;
            }

            return String.Empty;
        }

        /// <summary>
        ///   Gets the file icon.
        /// </summary>
        /// <param name = "extension">The extension.</param>
        /// <returns></returns>
        internal static string GetFileIcon(string extension)
        {
            foreach (var fileOpener in FileOpeners.Where(fileOpener => fileOpener.Extensions.Contains(extension)))
            {
                return String.Format("../../{0}/images/{1}", Constants.FileManagerFolderName, fileOpener.Icon);
            }

            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return String.Empty;
            }

            var node = configRoot.SelectSingleNode("filePages");

            var attribute = node.Attributes["defaultIcon"];
            var defaultIcon = String.Empty;

            if (attribute != null)
            {
                defaultIcon = String.Format("../../{0}/images/{1}", Constants.FileManagerFolderName, attribute.Value);
            }

            return defaultIcon;
        }

        /// <summary>
        ///   Gets the file node action.
        /// </summary>
        /// <param name = "fileInfo">The file info.</param>
        /// <returns></returns>
        internal static string GetFileNodeAction(FileInfo fileInfo)
        {
            var urlPath = Util.MapUrl(fileInfo.FullName);

            var extension = Util.GetSimpleExtension(fileInfo.Name).ToLower();

            foreach (var function in from fileOpener in FileOpeners
                                     where fileOpener.Extensions.Contains(extension)
                                     select Util.GetGoodFunctionName(fileOpener.Function))
            {
                return String.Format("{0}('{1}')", function, urlPath);
            }

            if (Instance.DocumentElement == null)
            {
                return String.Empty;
            }

            var node = Instance.DocumentElement.SelectSingleNode("filePages");

            var attribute = node.Attributes["defaultFunction"];

            if (attribute != null)
            {
                var function = Util.GetGoodFunctionName(attribute.Value);
                return String.Format("{0}('{1}')", function, urlPath);
            }

            return String.Empty;
        }

        /// <summary>
        ///   Gets the name of the file type.
        /// </summary>
        /// <param name = "extension">The extension.</param>
        /// <returns></returns>
        internal static string GetFileTypeName(string extension)
        {
            foreach (var fileOpener in FileOpeners.Where(fileOpener => fileOpener.Extensions.Contains(extension)))
            {
                return fileOpener.FileType;
            }

            return string.Format("{0} File", extension.ToUpper());
        }

        #endregion

        #region Private Properties

        /// <summary>
        ///   Gets the hidden folders paths.
        /// </summary>
        /// <value>The hidden folders paths.</value>
        private static ICollection<string> HiddenFolderPaths
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                if (configRoot == null)
                {
                    return new List<string>();
                }

                var node = configRoot.SelectSingleNode("globalHide");

                return node != null
                           ? Util.CleanLowerString(node.Attributes["folders"].Value).Split(',').ToList()
                           : new List<string>();
            }
        }

        /// <summary>
        ///   Gets the hidden files paths.
        /// </summary>
        /// <value>The hidden files paths.</value>
        private static ICollection<string> HiddenFilePaths
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                if (configRoot == null)
                {
                    return new List<string>();
                }
                var node = configRoot.SelectSingleNode("globalHide");

                return node != null
                           ? Util.CleanLowerString(node.Attributes["files"].Value).Split(',').ToList()
                           : new List<string>();
            }
        }

        /// <summary>
        ///   Gets the hidden file extensions.
        /// </summary>
        /// <value>The hidden file extensions.</value>
        private static ICollection<string> HiddenFileExtensions
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                if (configRoot == null)
                {
                    return new List<string>();
                }
                var node = configRoot.SelectSingleNode("globalHide");

                return node != null
                           ? Util.CleanLowerString(node.Attributes["extensions"].Value).Split(',').ToList()
                           : new List<string>();
            }
        }

        /// <summary>
        ///   Gets a value indicating whether [user permissions enabled].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [user permissions enabled]; otherwise, <c>false</c>.
        /// </value>
        private static bool UserPermissionsEnabled
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                return configRoot != null &&
                       Convert.ToBoolean(configRoot.SelectSingleNode("userPermissions").Attributes["enabled"].Value);
            }
        }

        /// <summary>
        ///   Gets a value indicating whether [section relations enabled].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [section relations enabled]; otherwise, <c>false</c>.
        /// </value>
        private static bool SectionRelationsEnabled
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                return configRoot != null &&
                       Convert.ToBoolean(configRoot.SelectSingleNode("sectionRelations").Attributes["enabled"].Value);
            }
        }

        /// <summary>
        ///   Gets a value indicating whether [global hide enabled].
        /// </summary>
        /// <value><c>true</c> if [global hide enabled]; otherwise, <c>false</c>.</value>
        private static bool GlobalHideEnabled
        {
            get
            {
                var configRoot = Instance.DocumentElement;
                return configRoot != null &&
                       Convert.ToBoolean(configRoot.SelectSingleNode("globalHide").Attributes["enabled"].Value);
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        ///   Gets the user folders.
        /// </summary>
        /// <param name = "userName">Name of the user.</param>
        /// <returns>Array of Folders</returns>
        private static ICollection<string> GetUserFolders(string userName)
        {
            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return new List<string>();
            }
            var node = configRoot.SelectSingleNode(String.Format("userPermissions/addUser[@name='{0}']", userName));

            return node != null
                       ? Util.CleanLowerString(node.Attributes["folders"].Value).Split(',').ToList()
                       : new List<string>();
        }

        /// <summary>
        ///   Gets the user files.
        /// </summary>
        /// <param name = "userName">Name of the user.</param>
        /// <returns>Array of Files</returns>
        private static ICollection<string> GetUserFiles(string userName)
        {
            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return new List<string>();
            }
            var node = configRoot.SelectSingleNode(String.Format("userPermissions/addUser[@name='{0}']", userName));

            return node != null
                       ? Util.CleanLowerString(node.Attributes["files"].Value).Split(',').ToList()
                       : new List<string>();
        }

        /// <summary>
        ///   Gets the user extensions.
        /// </summary>
        /// <param name = "userName">Name of the user.</param>
        /// <returns>Array of Extensions</returns>
        private static ICollection<string> GetUserExtensions(string userName)
        {
            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return new List<string>();
            }
            var node = configRoot.SelectSingleNode(String.Format("userPermissions/addUser[@name='{0}']", userName));

            return node != null
                       ? Util.CleanLowerString(node.Attributes["extensions"].Value).Split(',').ToList()
                       : new List<string>();
        }

        /// <summary>
        ///   Gets the user type folders.
        /// </summary>
        /// <param name = "userType">Type of the user.</param>
        /// <returns></returns>
        private static ICollection<string> GetUserTypeFolders(string userType)
        {
            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return new List<string>();
            }
            var node = configRoot.SelectSingleNode(String.Format("userPermissions/addUserType[@alias='{0}']", userType));

            return node != null
                       ? Util.CleanLowerString(node.Attributes["folders"].Value).Split(',').ToList()
                       : new List<string>();
        }

        /// <summary>
        ///   Gets the user type files.
        /// </summary>
        /// <param name = "userType">Name of the user.</param>
        /// <returns></returns>
        private static ICollection<string> GetUserTypeFiles(string userType)
        {
            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return new List<string>();
            }
            var node = configRoot.SelectSingleNode(String.Format("userPermissions/addUserType[@alias='{0}']", userType));

            return node != null ? Util.CleanLowerString(node.Attributes["files"].Value).Split(',') : new string[] { };
        }

        /// <summary>
        ///   Gets the user type extensions.
        /// </summary>
        /// <param name = "userType">Name of the user.</param>
        /// <returns></returns>
        private static ICollection<string> GetUserTypeExtensions(string userType)
        {
            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return new List<string>();
            }
            var node = configRoot.SelectSingleNode(String.Format("userPermissions/addUserType[@alias='{0}']", userType));

            return node != null
                       ? Util.CleanLowerString(node.Attributes["extensions"].Value).Split(',')
                       : new string[] { };
        }

        /// <summary>
        ///   Gets the section aliases from folder.
        /// </summary>
        /// <param name = "folderUrl">The folder URL.</param>
        /// <returns>Array Section Aliases</returns>
        private static ICollection<string> GetFolderSectionAliases(string folderUrl)
        {
            if (!SectionRelationsEnabled)
            {
                return new string[] { };
            }

            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return new List<string>();
            }
            var sectionNodes = configRoot.SelectSingleNode("sectionRelations").ChildNodes;

            var sectionAliases = new List<string>();

            sectionAliases.AddRange(
                from XmlNode node in sectionNodes
                let sectionFolders = Util.CleanLowerString(node.Attributes["folders"].Value).Split(',')
                where sectionFolders.Contains(folderUrl)
                select node.Attributes["alias"].Value);

            return sectionAliases;
        }

        /// <summary>
        ///   Gets the section aliases from file.
        /// </summary>
        /// <param name = "fileUrl">The file URL.</param>
        /// <returns>Array of Section Aliases</returns>
        private static ICollection<string> GetFileSectionAliases(string fileUrl)
        {
            if (!UmbracoTreesEnabled)
            {
                return new string[] { };
            }

            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return new List<string>();
            }
            var sectionNodes = configRoot.SelectSingleNode("sectionRelations").ChildNodes;

            var sectionAliases = new List<string>();

            sectionAliases.AddRange(
                from XmlNode node in sectionNodes
                let sectionFolders = Util.CleanLowerString(node.Attributes["files"].Value).Split(',')
                where sectionFolders.Contains(fileUrl)
                select node.Attributes["alias"].Value);

            return sectionAliases;
        }

        /// <summary>
        ///   Gets the section aliases from extension.
        /// </summary>
        /// <param name = "extension">The extension.</param>
        /// <returns>Array of Section Aliases</returns>
        private static ICollection<string> GetExtensionSectionAliases(string extension)
        {
            if (!UmbracoTreesEnabled)
            {
                return new string[] { };
            }

            var configRoot = Instance.DocumentElement;
            if (configRoot == null)
            {
                return new List<string>();
            }
            var sectionNodes = configRoot.SelectSingleNode("sectionRelations").ChildNodes;

            var sectionAliases = new List<string>();

            sectionAliases.AddRange(
                from XmlNode node in sectionNodes
                let sectionFolders = Util.CleanLowerString(node.Attributes["extensions"].Value).Split(',')
                where sectionFolders.Contains(extension)
                select node.Attributes["alias"].Value);

            return sectionAliases;
        }

        #endregion
    }
}